import { addLayer, removeLayer, LayerConfig, LayerType, updateSource } from "../../layer/layerManage";
import { getLayerManagerState } from "../../layer/layerManagerState";

interface LabelResources {
  id: string;
}

// 加载geojson 图标
export function loadGeojsonIcon(map: any, id: string, geojsonData: any) {
  const source = {
    type: LayerType.geojson,
    data: geojsonData
  };
  // 添加图层显示点标记
  const layerOptions: LayerConfig = {
    id: id,
    type: LayerType.Symbol,
    source,
    layout: {
      "icon-image": ["get", "iconName"], // 使用Mapbox默认图标
      "icon-size": 0.4,
      "text-field": ["concat", ["get", "T"], "℃"],
      "text-offset": [0, 1.5],
      "text-anchor": "top",
      "text-size": 14, // 设置文字大小
      "text-font": ["MicrosoftYaHei"] // 设置字体
    },
    paint: {
      "icon-color": "#2262CC" // 自定义图标颜色
    }
  };
  addLayer(getLayerManagerState(map), layerOptions);

  // 返回资源对象，用于后续释放
  return {
    id
  };
}

// 导出一个函数，用于释放标签
export function releaseIcons(map: any, resources: LabelResources): void {
  // 从resources中解构出id、dragHandler和zoomHandler
  const { id, dragHandler, zoomHandler } = resources;

  // 移除事件监听
  if (dragHandler) {
    // 移除moveend事件监听
    map.off("moveend", dragHandler);
  }
  if (zoomHandler) {
    // 移除zoomend事件监听
    map.off("zoomend", zoomHandler);
  }

  // 移除图层和源
  removeLayer(getLayerManagerState(map), id);
}

// 更新geojson图标数据
export function updateGeojsonIcon(map: any, id: string, geojsonData: any) {
  updateSource(getLayerManagerState(map), id, geojsonData);
}
